# -*- coding: utf-8 -*-
# @Time : 2023/11/22 11:40
# @Author : ZH
# @File : photon.py
# @Software: PyCharm
import requests
import json


class Photon:
    def __init__(self, proxies: dict, **kwargs):
        """

        :param proxies: 代理
            proxies = {
                'http': 'http://127.0.0.1:7890',
                'https': 'http://127.0.0.1:7890'
                }
        """
        self.proxies = proxies

    @classmethod
    def get_support(cls):
        support = ['en']
        return support

    def start_main(self, location: str, limit=5, timeout=10, **kwargs):
        # 纬度（lat）
        # 经度（lon）
        headers = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Origin': 'https://www.maps.ie',
            'Pragma': 'no-cache',
            'Referer': 'https://www.maps.ie/coordinates.html',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'cross-site',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
            'sec-ch-ua': '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
        }
        params = {
            'lang': 'en',
            'limit': f'{limit}',
            'q': location
        }
        for i in range(3):
            try:
                response = requests.get('https://photon.komoot.io/api/', params=params, headers=headers,
                                        timeout=timeout,
                                        proxies=self.proxies)
                data = json.loads(response.text)
                features = data.get('features', [{}])
                return [{"lon": data.get('geometry', {}).get('coordinates', [])[0],
                         "lat": data.get('geometry', {}).get('coordinates', [])[1],
                         "country": data.get('properties', {}).get('country'),
                         "name": data.get('properties', {}).get('name')} for data in features]
            except:
                pass
        return None

